package com.haidong.myfile;

import java.util.ArrayList;
import java.util.List;

/**
 * 这个类作为文件或目录的类
 */
public class MyFile {
    private String name;
    private User user;
    public int isFile;//默认值为文件夹
    private String data = "默认文字";//文件内容,文件夹不需要
    private MyFile father;//通过记录父节点的对象来追溯自己的位置
    private List<MyFile> sons = new ArrayList<>();
    //使用二维集合存放文件的权限,默认所有者满权限,同组人只读不写,其他人只有执行权
    private int[][] permission = {{1,1,1},{1,0,1},{0,0,1}};

    public MyFile(String name) {
        this.name = name;
    }
    public MyFile(String name,MyFile father){
        this(name);
        this.father = father;
        //添加父属性的同时给父对象加子属性
        father.getSons().add(this);
    }
    public MyFile(String name,MyFile father,User user){
        this(name,father);
        this.user = user;
        this.isFile = 1;
    }

    //显示绝对路径,列举目录负责调用,通过递归显示自己的绝对路径
    public String showPath(){
        if(father==null) return name + ":";
        else{
            return father.showPath() + "\\" + name;
        }
    }

    //输出自己的权限编码,用来列目录时使用
    public String showPermission(){
        String permit = "";
        for (int i = 0; i < 3; i++) {
            for(int j = 0;j < 3;j++){
                if(permission[i][j]==1){
                    if(j==0) permit += "4";
                    else if(j==1) permit += "2";
                    else permit += "1";
                }else permit += "0";
            }
        }
        return permit;
    }

    //身份识别,获取主调的身份
    public int identify(User user){
        if(user==this.user) return 0;
        else if(this.user.getGroup()==user.getGroup()) return 1;
        else return 2;
    }

    //显示该文件/夹的属性
    public String showDetail(){
        String detail = "";
        detail += name + "\t" + showPath() + "\t\t\t"
                + showPermission() + "\t" + data.length() + "\n";
        return detail;
    }

    //实现对当前文件的读功能
    public String read(User user){
        String readData = "";
        if(permission[identify(user)][0]!=1){
            return "你没有读该文件的权限!\n";
        }
        return data + "\n";
    }

    //获取用户是否有写入权限
    public String write(User user){
        if(permission[identify(user)][1]!=1){
            return "你没有写该文件的权限!\n";
        }else{
            return "请输入写入的内容:";
        }
    }
    //在用户获得写权限后,真正执行写操作
    public void write2(String writeData){
        data = writeData;
    }

    public String getName() {
        return name;
    }
    public MyFile getFather() {
        return father;
    }
    public List<MyFile> getSons() {
        return sons;
    }
    public String getData(){
        return data;
    }
    public User getUser() {return user;}
    public void setPermission(int[][] permission) {this.permission = permission;}
}
